/*
 * @Author: dgflash
 * @Date: 2022-04-21 13:45:51
 * @LastEditors: wangjinyan
 * @LastEditTime: 2022-11-02 16:21:17
 */
import { IProtocolHelper, IRequestProtocol, IResponseProtocol, NetData } from "./NetInterface";

function unzip(str: string) {
	const charData = str.split('').map(function (x) {
		return x.charCodeAt(0);
	});

	const binData = new Uint8Array(charData);
	// @ts-ignore
	const data = pako.inflate(binData, { to: 'string' });

	return data;
}

function zip(str: string) {
	// @ts-ignore
	const binaryString = pako.gzip(str, { to: 'string' });

	return binaryString;
}

/** Pako.js 数据压缩协议 */
export class NetProtocolPako implements IProtocolHelper {
	getMsgId(msg: IResponseProtocol): number {
		throw new Error("Method not implemented.");
	}

	getSeq(msg: IResponseProtocol): string {
		throw new Error("Method not implemented.");
	}

	getHeadlen(): number {
		return 0;
	}

	getHearbeat(): NetData {
		return "";
	}

	getPackageLen(msg: NetData): number {
		return msg.toString().length;
	}

	checkResponsePackage(respProtocol: IResponseProtocol): boolean {
		return true;
	}

	handlerResponsePackage(respProtocol: IResponseProtocol): boolean {
		if (respProtocol.code == 1) {
			if (respProtocol.isCompress) {
				respProtocol.data = unzip(respProtocol.data);
			}

			respProtocol.data = JSON.parse(respProtocol.data);

			return true;
		}
		else {
			return false;
		}
	}

	handlerRequestPackage(reqProtocol: IRequestProtocol): string {
		const rspCmd = reqProtocol.action + "_" + reqProtocol.method;

		reqProtocol.callback = rspCmd;
		if (reqProtocol.isCompress) {
			reqProtocol.data = zip(reqProtocol.data);
		}

		return rspCmd;
	}

	getPackageId(respProtocol: IResponseProtocol): string {
		return respProtocol.callback!;
	}
}